package com.nanbei.thread;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @ClassDescription: ThreadLocal使用案例
 * @JdkVersion: 1.8
 * @Author: libs
 * @Created: 2024/10/11 10:10
 */
public class ThreadLocalDemo {
    public static void main(String[] args) {
        ThreadLocal<Integer> threadLocal = ThreadLocal.withInitial(() -> 1);
        ExecutorService threadPool = Executors.newFixedThreadPool(3);

        // newThread(threadLocal);
        for (int i = 0; i < 10; i++) {
            threadPool.execute(()->{
                try {
                    Integer bef = threadLocal.get();
                    threadLocal.set(threadLocal.get()+1);
                    System.out.println("当前线程"+Thread.currentThread().getName()+"计算前的值为："+bef+
                            "   当前线程"+Thread.currentThread().getName()+"计算后的值为："+ threadLocal.get());
                } catch (Exception e) {
                    e.printStackTrace();
                }finally {
                    // 因为线程池中的线程是多个线程共同使用的
                    // threadLocal 在线程池中如果不进行删除会造成内存泄露，还会在多线程之间照成数据干扰等问题
                    threadLocal.remove();
                }
            });
        }

    }

    private static void newThread(ThreadLocal<Integer> threadLocal) {
        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                Integer bef = threadLocal.get();
                threadLocal.set(threadLocal.get()+1);
                System.out.println("当前线程"+Thread.currentThread().getName()+"计算前的值为："+bef+
                        "   当前线程"+Thread.currentThread().getName()+"计算后的值为："+ threadLocal.get());
            },String.valueOf(i)).start();
        }
    }
}
